package com.lmabbe.core.service.impls;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmabbe.common.datasources.plugin.TenantMasterSlaveAutoRoutingPlugin;
import com.lmabbe.core.common.entitys.SysRole;
import com.lmabbe.core.common.entitys.SysUser;
import com.lmabbe.core.common.entitys.SysUserRole;
import com.lmabbe.core.common.interfaces.SysUserService;
import com.lmabbe.core.common.query.SysUserQuery;
import com.lmabbe.core.service.dao.SysRoleMapper;
import com.lmabbe.core.service.dao.SysUserMapper;
import com.lmabbe.core.service.dao.SysUserRoleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.rpc.RpcContext;

import java.util.List;

/**
 * @author lmabbe
 */
@Slf4j
@DubboService(provider = "simple-dubbo")
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserMapper sysUserMapper;
    private final SysUserRoleMapper sysUserRoleMapper;
    private final SysRoleMapper sysRoleMapper;

    @Override
    public SysUser findByUserAccount(String userAccount) {
        return sysUserMapper.findUserAccount(userAccount);
    }

    @Override
    public SysUser findByUserMobile(String mobile) {
        return sysUserMapper.findByUserMobile(mobile);
    }

    @Override
    public IPage selectPage(SysUserQuery query) {
        return baseMapper.selectPage(query.createPage(), query.createQuery());
    }

    @Override
    public SysRole getUserRole(Long userId) {
        RpcContext context = RpcContext.getContext();
        TenantMasterSlaveAutoRoutingPlugin.rpcContextThreadLocal.set(context);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(sysUserRoleMapper.createQueryWrapper().eq(SysUserRole::getUserId, userId));
        if (sysUserRoles.size() == 0) {
            return null;
        } else {
            return sysRoleMapper.selectOne(sysRoleMapper.createQueryWrapper().eq(SysRole::getRoleId, sysUserRoles.get(0).getRoleId()));
        }
    }
}
